# -*- coding: utf8 -*-


import sys
import argparse

from os.path import splitext

from .utils import get_first, set_default_ext

_APP_VERSION = '0.1.0'


def _parse_args(
    args
) -> argparse.Namespace:
    r''' 解析命令行参数。
    '''
    parser = argparse.ArgumentParser(prog='nau', add_help=False)
    parser.add_argument('--dsn', action='store', dest='dsn', metavar='DATABASE_CONNECTION_STRING', default='')
    parser.add_argument('action', action='store', nargs=1, metavar='ACTION', choices=('doc', 'sql',),
                        help='doc: Generate xls file from database; sql: Generate sql file from xls')
    parser.add_argument('doc_path', action='store', nargs=1, metavar='DOC_PATH')
    parser.add_argument('sql_path', action='store', nargs='?', metavar='SQL_PATH', default='')
    parser.add_argument('drop_cascade', action='store', nargs='?', metavar='DROP_CASCADE', default=False, type=bool)
    pg = parser.add_mutually_exclusive_group(required=False)
    pg.add_argument('--help', action='help', help='Show this help message and quit')
    pg.add_argument('--version', action='version', version='%(prog)s ' + _APP_VERSION, help='Show version message and quit')
    pg.add_argument('--verbose', action='store_true', help='Show verbose information')

    return parser.parse_args()


def main(
    argv
) -> int:
    r''' 脚本主入口。

    : param argv: 命令行参数。
    : return: 执行脚本的返回值。
    '''
    args = _parse_args(argv)
    action = args.action[0]

    doc_path = set_default_ext(get_first(args.doc_path), '.xlsx')
    sql_path = set_default_ext(args.sql_path, '.sql')

    if action == 'doc':
        from .doc import execute
        execute(dsn=args.dsn, doc_path=doc_path, verbose=args.verbose)
    elif action == 'sql':
        from .sql import execute
        execute(dsn=args.dsn, doc_path=doc_path, sql_path=sql_path, verbose=args.verbose, drop_cascade = args.drop_cascade)
    else:
        raise ValueError('Unknown action: {!r:}'.format(action))


if __name__ == '__main__':
    exit(main(sys.argv))
